package zx.springcloud.util;

/**
 * @author ZX
 * @date 2021/3/18
 */
public class CounterDemo
{
    /**
     * 计数器是一种比较简单的限流算法，用途比较广泛，在接口层面，很多地方使用这种方式限流。在一段时间内，进行计数，与阀值进行比较，到了时间临界点，将计数器清0。
     */
    private static long timeStamp = System.currentTimeMillis();
    //限制1S内请求数量100
    private static long limitCount = 100;
    private static long interval = 1000;
    //请求数量
    private static long reqCount = 0;
    private static long i = 0;
    public static boolean grant()
    {
        System.out.println(reqCount);

        long now = System.currentTimeMillis();
        if (now < timeStamp + interval)
        {
            if (reqCount < limitCount)
            {

                ++reqCount;
                return true;

            }
            else
            {
                return false;
            }

        }
        else
        {
            timeStamp = System.currentTimeMillis();
            reqCount = 0;
            return false;
        }
    }

    public static void grant1(){

       /* int i=0;*/
        System.out.println(++i);
    }

    public static void main(String[] args) throws InterruptedException
    {
       /* for (int i = 0; i < 500; i++)
        {
            new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    if (grant())
                    {
                        System.out.println("执行业务");
                    }
                    else
                    {
                        System.out.println("限流");
                    }

                }
            }).start();

        }*/
        grant();
        Thread.sleep(10000);
        grant();
    }

}
